const router = require('koa-router')()
const models = require('../models')
const moment = require('moment')
const Sequelize = require('sequelize');
const Op = Sequelize.Op;

router.post('/apply', async ctx => {
    let name = Math.random()
    let sex = ctx.request.body.sex
    let phone = 17645117357
    let wx = ctx.request.body.wechat
    let live = ctx.request.body.is_thehost
    let content = ctx.request.body.introduce
    let img = ctx.request.body.img

    await models.test.create({
        name,
        sex,
        phone,
        wx,
        live,
        content,
        img,
        created_at: Date.parse(new Date())/1000
    })

    ctx.body = {
        code: 200,
        msg: '操作成功'
    }
})

router.post('/apply_list', async ctx => {
    let page = ctx.request.body.page
    let pageshow = ctx.request.body.pageshow
    let sex = ctx.request.body.sex
    let stime = moment(ctx.request.body.stime).unix()
    let etime = moment(ctx.request.body.etime).unix()
    let condition = {}
    
    if (!sex == '') {
        Object.assign(condition, {sex})
    }
    if (stime && etime) {
        Object.assign(condition, {
            created_at: {
                [Op.between]: [stime, etime]
            }
        })
    }
    let user = await models.test.findAndCountAll({
        where: condition,
        order: [
            ['created_at', 'DESC'],
        ],
        limit: pageshow,
        offset: (page - 1)*pageshow
    })

    return ctx.body = {
        code: 200,
        data: {
            list: user.rows.map(item => {
                let obj = JSON.parse(JSON.stringify(item))
                return {
                    ...obj,
                    created_at: moment(obj.created_at*1000).format('YYYY-MM-DD HH:mm:ss')
                }
            }),
            count: user.count
        },
        msg: '操作成功'
    }
})

module.exports = router